package com.zxl.yjb.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;

import com.zxl.yjb.R;

import java.util.List;


/**
 * 当Activity中的Fragment以流式进行交互时,继承该AppActivity
 */
public abstract class AppActivity extends BaseActivity {

    //处理Intent
    protected void processIntent(Intent intent){}

    //获取添加的Fragment的实例
    protected abstract BaseFragment getFragmentInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        if(getIntent()!=null){
            processIntent(getIntent());
        }
        List<Fragment> fragments=getSupportFragmentManager().getFragments();
        if(fragments==null||fragments.size()==0){//向Activity中添加第一个Fragment
            BaseFragment firstFragment=getFragmentInstance();
            if(firstFragment!=null){
                addFragment(firstFragment);
            }
        }
    }

    protected int getContentViewId() {
        return R.layout.activity_app;
    }

    protected int getFragmentContentId() {
        return R.id.fragment_container;
    }

    /**
     * 向Activity中添加Fragment
     * @param fragment
     */
    protected void addFragment(BaseFragment fragment){
        if(fragment!=null){
            getSupportFragmentManager().beginTransaction()
                    .replace(getFragmentContentId(),fragment,fragment.getClass().getSimpleName())
                    .addToBackStack(fragment.getClass().getSimpleName())
                    .commitAllowingStateLoss();
        }
    }

    /**
     * 将Fragment移出Activity
     */
    protected void removeFragment(){
        if(getSupportFragmentManager().getBackStackEntryCount()>1){
            getSupportFragmentManager().popBackStack();
        }else{
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==event.KEYCODE_BACK){
            if(getSupportFragmentManager().getBackStackEntryCount()==1){
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
